package com.atguigu.gmall.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.order.entity.OrderInfo;
import com.atguigu.gmall.pay.config.properties.AlipayProperties;
import com.atguigu.gmall.pay.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class payServiceImpl  implements PayService {

    @Autowired
    AlipayClient  alipayClient;
    @Autowired
    OrderFeignClient client;
    @Autowired
    AlipayProperties  alipayProperties;
    @Override
    public String generatePaypage(Long orderId, Long userId) throws AlipayApiException {
        //1 得到阿里支付客户端
//        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl,
//                AlipayConfig.app_id,
//                AlipayConfig.merchant_private_key,
//                "json",
//                AlipayConfig.charset,
//                AlipayConfig.alipay_public_key,
//                AlipayConfig.sign_type);

        // TODO 2 创建一个支付请求
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // TODO 3 设置参数
        alipayRequest.setReturnUrl(alipayProperties.getReturn_url());  //同步回调 支付成功以后  浏览器要挑战页面
        alipayRequest.setNotifyUrl(alipayProperties.getNotify_url());  //通知回调  支付成功以后   支付消息会通知给该地址
        //TODO 4 准备待支付的订单数据
        OrderInfo orderInfo = client.getOrderById(orderId).getData();
         // 商户订单号
        String tradeNo = orderInfo.getOutTradeNo();
        //付款金额
        BigDecimal totalAmount = orderInfo.getTotalAmount();
        //订单名称
        String orderName="云边小卖部"+tradeNo;
        //商品描述
        String tradeBody = orderInfo.getTradeBody();
        //业务参数
        Map<String,Object> bizContent = new HashMap<>();
        bizContent.put("out_trade_no",tradeNo);
        bizContent.put("total_amount",totalAmount);
        bizContent.put("subject",orderName);
        bizContent.put("body",tradeBody);
        bizContent.put("product_code","FAST_INSTANT_TRADE_PAY");
        //TODO 自动关单
        String date = DateUtil.formatDate(orderInfo.getExpireTime(), "yyyy-MM-dd HH:mm:ss");
        bizContent.put("time_expire",date);
        //自动关单
//        String date = DateUtil.formatDate(orderInfo.getExpireTime(), "yyyy-MM-dd HH:mm:ss");
//        bizContent.put("time_expire",date);
        alipayRequest.setBizContent(JSON.toJSONString(bizContent));
        //生成支付页面
        String page = alipayClient.pageExecute(alipayRequest).getBody();
        return page;
    }
}
